package com.example.rdb.handle.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * @author XYC
 * @描述: TODO
 * @date 20.12.214:12
 */
@Component
public class RedisMoveAll {

    @Autowired
    @Qualifier(value = "defaultRedisTemplate")
    private RedisTemplate<String, Object> defaultTemplate;

    @Autowired
    @Qualifier(value = "cacheRedisTemplate")
    private RedisTemplate<String, Object> targetTemplate;


    public void typeKey() {
        Set<String> keys = defaultTemplate.keys("*");
        keys.forEach(key -> {
            DataType type = defaultTemplate.type(key);
            switch (type) {
                case LIST:
                    listKey(key);
                    break;
                case HASH:
                    hashKey(key);
                    break;
                case STRING:
                    stringKey(key);
                    break;
                case NONE:
                    System.out.println(key + ": 读取失败");
                    break;
            }
        });
        System.out.println("------SUCCESS------");
    }


    public void stringKey(String key) {
        Object value = defaultTemplate.opsForValue().get(key);
        targetTemplate.opsForValue().set(key, value);
    }

    public void hashKey(String key) {
        Map<Object, Object> values = defaultTemplate.opsForHash().entries(key);
        targetTemplate.opsForHash().putAll(key,values);
    }

    public void listKey(String key) {
        Long size = defaultTemplate.opsForList().size(key);
        List<Object> values = defaultTemplate.opsForList().range(key, 0, size);
        targetTemplate.opsForList().rightPushAll(key,values);
        System.out.println("------PUSH SUCCESS------");
    }
}
